#include <stdio.h>
#include <locale.h>
#include <sys/types.h>	       /* See NOTES */
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/can/raw.h>
#include <net/if.h>
#include <string.h>
#include <unistd.h>

#define CAN_MTU (sizeof(struct can_frame)) 

#define CAN_DEVICE "vcan0" 
int main(int argc, const char *argv[])
{
	int can_sockfd;
	struct sockaddr_can can_addr;
	struct ifreq ifr;

	setlocale(LC_ALL, "");

	can_sockfd = socket(AF_CAN, SOCK_RAW, CAN_RAW);

	strcpy(ifr.ifr_name, CAN_DEVICE);
	ioctl(can_sockfd, SIOCGIFINDEX, &ifr);

	memset(&can_addr, 0, sizeof(can_addr));
	can_addr.can_family = AF_CAN;
	can_addr.can_ifindex = ifr.ifr_ifindex;

	/* CAN_RAW LOOPBACK Option */
	int loopback = 1;
	setsockopt(can_sockfd, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback, sizeof(loopback));

	bind(can_sockfd, (struct sockaddr *)&can_addr, sizeof(can_addr));

	struct can_frame frame;
	int ret = -1;
	frame.can_id = 4;
	frame.can_dlc = 3;
	frame.data[0] = 'a';
	frame.data[1] = 'c';
	frame.data[2] = 'k';
	ret = write(can_sockfd, &frame, CAN_MTU);
	if (ret < 0) {
		perror("can raw socket write");
		return -1;
	}
	if (ret < CAN_MTU) {
		fprintf(stderr, "write: incomplete CAN frame\n");
		return -1;
	}

	return 0;
}

int can_read(int can_sockfd, struct can_frame *frame)
{
	int ret = -1;
	
	ret = read(can_sockfd, frame, CAN_MTU);

	return ret;
}
